#!/bin/bash
# date: 2022/11/22
# auth: frealess11
# desc: install alertmanager
# doc: https://github.com/prometheus/alertmanager

ip_local=$(/usr/sbin/ip add | grep inet | grep global | grep -Ev 'docker' | awk '{print $2}' | awk -F/ '{print $1}' | tail -1)
port=9093
addr=${ip_local}:${port}
docker_name="alertmanager_${port}"
image="prom/alertmanager:v0.24.0"
conf=$(pwd)/conf

docker_start() {
  docker run -d \
    --name ${docker_name} \
    -m 800m \
    --net=host \
    --restart=always \
    --log-opt max-size=100m \
    --log-opt max-file=10 \
    -u root \
    -v ${conf}:/etc/alertmanager \
    ${image} \
    --config.file=/etc/alertmanager/alertmanager.yaml \
    --cluster.advertise-address=0.0.0.0:${port}
}

docker_stop() {
  docker stop ${docker_name}
  docker rm ${docker_name}
}

docker_exec() {
  docker exec -it ${docker_name} sh
}

docker_logs() {
  docker logs --tail=10 ${docker_name}
}

alert_metrics() {
  curl -s -XGET http://${addr}/metrics
}

alert_send() {
  content='[
    {
        "labels":{
            "alertname":"mock-alert-send",
            "env":"dev",
            "biz":"erp"
        },
        "annotations":{
            "info":"the dev erp down"
        }
    },
    {
        "labels":{
            "alertname":"test-disk",
            "env":"dev",
            "biz":"erp",
            "instance":"127.0.0.1",
            "severity":"critical"
        }
    }
]'
  curl -XPOST -d"$content" http://${addr}/api/v1/alerts
}

case $1 in
start)
  docker_start
  ;;
stop)
  docker_stop
  ;;
exec)
  docker_exec
  ;;
logs)
  docker_logs
  ;;
metrics)
  alert_metrics
  ;;
send)
  alert_send
  ;;
*)
  echo "$0 start|stop|exec|logs|metric|send"
  ;;
esac
